import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Login from '@/views/login'
import Layout from '@/views/layout'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirectTo: '/',
      children: [
        // { path: '', component: Home },
        { path: '/', component: () => import('@/views/layout/components/Home'), meta: { isKeepAlive: true } },
        { path: '/question', component: () => import('@/views/layout/components/Question') },
        // { path: '/question', component: Question },
        { path: '/video', component: () => import('@/views/layout/components/Video') },
        { path: '/user', component: () => import('@/views/layout/components/User'), meta: { isKeepAlive: true } }

      ]
    },
    { path: '/search', component: () => import('@/views/search') },
    { path: '/searchResult', component: () => import('@/views/search/result.vue') },
    { path: '/article/:id', component: () => import('@/views/article'), name: 'article' },
    { path: '/profile', component: () => import('@/views/layout/components/User/profile.vue'), name: 'profile' },
    { path: '/userChat', component: () => import('@/views/layout/components/User/chat.vue') }
  ]
})

// 需要认证的页面
const AuthUrls = ['/user']
// 全局前置守卫: 所有的路由在真正被访问前, 都会先经过全局前置守卫, 让全局前置守卫放行了, 才会继续访问到路由
// 如果要去的页面, 是需要授权才能访问的页面, 那么就需要判断是否token
router.beforeEach((to, from, next) => {
  const token = store.state.user.userToken.token
  // 如果是去 /login, 判断 token 存不存在, 如果 token 存在说明登录过了, 直接跳转到首页
  if (to.path === '/login' && token) {
    next('/')
    return
  }
  // 判断要去的页面, 是否需要授权
  if (AuthUrls.includes(to.path)) {
    if (token) {
      // 有token, 有票
      next()
    } else {
      // 想去需要授权的页面, 且没有token, 拦截到登录
      // next('/login')
      next({
        path: '/login',
        // 这里传递的参数, 会被拼接到跳转的路由上
        query: {
          backto: to.fullPath
        }
      })
    }
  } else {
    // 不需要授权即可访问
    next()
  }
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// -重写路由中push方法  捕获push方法异常   vue路由3.x的问题  4.x已经解决这个问题了
export default router
